﻿using Bnbjoy.Business.Abstract;
using Bnbjoy.Business.Concrete;
using Bnbjoy.Business.Model;
using Bnbjoy.Domain.Abstract;
using Bnbjoy.Domain.Concrete;
using BnbjoyBackend.Api.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace BnbjoyBackend.Api.Controllers
{
    [Authorize]
    public class CaptchaController : ApiController
    {
        [Route("api/captcha/mobile")]
        [HttpPost]
        public async Task<HttpPostResponse> Mobile([FromBody]SendMobileCaptchaParam param)
        {
            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values
                 .SelectMany(v => v.Errors)
                 .Select(e => e.ErrorMessage));
                 return new HttpPostResponse(HttpStatusCode.BadRequest, message);
            }

            using (IAccountService accountService = new AccountService<IUserRepository>(new UserRepository()))
            {
                var user = await accountService.FindUser(param.MobileNumber);
                if (user != null)
                {
                    return new HttpPostResponse(HttpStatusCode.BadRequest, string.Format("手机号{0}已被注册", param.MobileNumber));
                }
            }

            using (IMobileCaptchaService mobileCaptchaService = new MobileCaptchaService(new MobileCaptchaRepository()))
            {
                bool result = await mobileCaptchaService.SendMobileCaptcha(param.MobileNumber);
                if (result)
                    return new HttpPostResponse(HttpStatusCode.OK, string.Format("验证码已发送至手机{0}", param.MobileNumber));
                else
                    return new HttpPostResponse(HttpStatusCode.Forbidden, "发送失败");
            }
        }



    }
}
